package com.aoxin.controller.system;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aoxin.mapper.opm.SlfUserMapper;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import reactor.core.scheduler.Scheduler;

import com.aoxin.mapper.SlfChildExpectedTimeMapper;
import com.aoxin.mapper.SlfClassCourseNumberMapper;
import com.aoxin.mapper.SlfClassroomEmployMapper;
import com.aoxin.mapper.SlfUserCourseConditionMapper;
import com.aoxin.mapper.course.systemCourse.AloneCourseDao;
import com.aoxin.mapper.course.systemCourse.AloneCoursePageDao;
import com.aoxin.mapper.course.systemCourse.SchoolCourseDao;
import com.aoxin.mapper.course.systemCourse.SchoolCoursePageDao;
import com.aoxin.mapper.course.systemCourse.SchoolCourseToPageDao;
import com.aoxin.mapper.course.webCourse.MyCoursePageMapper;
import com.aoxin.mapper.course.webCourse.SlfChildrenMapper;
import com.aoxin.mapper.opm.SlfClassroomMapper;
import com.aoxin.model.SlfChildExpectedTime;
import com.aoxin.model.SlfClassroomEmploy;
import com.aoxin.model.SlfUserCourseCondition;
import com.aoxin.model.course.AloneCourse;
import com.aoxin.model.course.AloneCoursePage;
import com.aoxin.model.course.SchoolCourse;
import com.aoxin.model.course.SchoolCoursePage;
import com.aoxin.model.course.SlfChildren;
import com.aoxin.model.course.SlfMyCoursePage;
import com.aoxin.model.dto.UserDto;
import com.aoxin.model.opm.SlfClassroom;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.course.webCourse.ChildrenService;
import com.aoxin.service.inter.opm.UserService;
import com.aoxin.service.inter.system.CommonService;
import com.aoxin.util.AjaxRes;
import com.aoxin.util.CommonUtil;
import com.aoxin.util.Const;
import com.aoxin.util.CookieUtil;
import com.aoxin.util.DateWay;
import com.aoxin.util.ErrorUtil;
import com.aoxin.util.ThreadLocalUtil;

/**
 * 公共Controller
 * 
 * @author Melody
 * @date 2018年4月1日 下午3:16:13
 */
@Controller
@RequestMapping("/web")
@ResponseBody
public class CommonController {

	@Autowired
	private CommonService commonService;
	@Autowired
	private SlfClassroomMapper slfClassroomMapper;
	@Autowired
	private SchoolCoursePageDao schoolCoursePageDao;
	@Autowired
	private SlfChildExpectedTimeMapper slfChildExpectedTimeMapper;
	@Autowired
	private SlfClassroomEmployMapper slfClassroomEmployMapper;
	@Autowired
	private SchoolCourseToPageDao schoolCourseToPageDaoMapper;
	@Autowired
	private SlfUserCourseConditionMapper slfUserCourseConditionMapper;
	@Autowired
	private SchoolCourseDao schoolCourseMapper;
	@Autowired
	private SlfChildrenMapper slfChildrenMapper;
	@Autowired
	private UserService userService;
	@Autowired
    private SlfClassCourseNumberMapper slfClassCourseNumberMapper;
	@Autowired
	private AloneCoursePageDao aloneCoursePageDao;
	@Autowired
	private MyCoursePageMapper myCoursePageMapper;
	@Autowired
	private AloneCourseDao aloneCourseDao;
	@Autowired
    ChildrenService childrenService; 
	
	// 判断用户是否登陆
	@RequestMapping("/firstLogin")
	public String isLogin(HttpServletRequest request, HttpServletResponse response) {
        String phone=null;
        String reMsg = "";
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("userSession");
        if(null != obj) {
        	SlfUser user = (SlfUser)obj;
        	Integer userid = user.getUserId();
        	user = userService.getUser(userid);
        	session.setAttribute("userSession", user);
        	reMsg = "1";
        	return reMsg;
        }else {
        	Cookie cookies[] = request.getCookies();
            if(cookies!=null){
                for(int i=0;i<cookies.length;i++){
                    if(cookies[i].getName().equals(CookieUtil.COOKIE_NAME)){
                        phone=cookies[i].getValue();
                    }
                }
            }else{
				System.err.println("=======================");
			}
            System.out.println(""+phone);
            
            if(phone!=null){
            	SlfUser user = userService.getUser(Integer.parseInt(phone));
            	if(user!=null){
            		session.setAttribute("userSession", user);
                    //已经登录过的用户
                    reMsg="1";	
            	}else{
            		 reMsg = "0";
            	}
            }else{
                reMsg = "0";
            }
    		return reMsg;
        }
	}
	  /**
	    * 排班,排课(定时,判断用户是否登陆)
	    */
		Integer ranks = 0;
//		@Scheduled(cron = "0/30 * * * * *") 
//		@Scheduled(cron = "0 0 0 1/3 * ?") //凌晨零点执行(隔三天)
		@RequestMapping("/teachingScheduleClick")
		@Transactional
		public String isLogin() throws ParseException{
			List<SchoolCoursePage> schoolCoursePage = schoolCoursePageDao.getAloneCoursePages();
			List<SchoolCoursePage> schoolCoursePages = new ArrayList<SchoolCoursePage>();
			//得到课程
			for(int i = 0;i<schoolCoursePage.size();i++){
			if(schoolCoursePage.get(i).getParentId()==null){
				schoolCoursePage.get(i).setParentId(0);
			}
			SchoolCoursePage SchoolModel = new SchoolCoursePage(); 
	        Integer rank = Getpackaging(schoolCoursePage.get(i).getParentId());
	        SchoolModel.setRank(rank);
	        SchoolModel.setName(schoolCoursePage.get(i).getName());
	        SchoolModel.setSchoolCoursePageId(schoolCoursePage.get(i).getSchoolCoursePageId());
	        SchoolModel.setCoursePageId(schoolCoursePage.get(i).getCoursePageId());
	        if(schoolCoursePage.get(i).getParentId()!=null){
	        SchoolModel.setParentId(schoolCoursePage.get(i).getParentId());
	        }else{
	        SchoolModel.setParentId(0);
	        }
	        schoolCoursePages.add(SchoolModel);
	        ranks = 0;
			}
			//排序(倒序)
			schoolCoursePages.sort(new Comparator<SchoolCoursePage>() {//Comparator 比较器. 需要实现比较方法
	            @Override
	            public int compare(SchoolCoursePage o1, SchoolCoursePage o2) {
	                return o2.getRank()-o1.getRank();//从大到小
	            }
	        });
			//用来保存已经被排除了的孩子ID(用于后面时间排除这些ID)
			Map<String,Object> map = new HashMap<String,Object>();
			//课程包循环
			for(int i = 0;i<schoolCoursePages.size();i++){
				//所有教室(绑定了包的)
				Integer SchoolCoursePageId = schoolCoursePages.get(i).getSchoolCoursePageId();
				List<SlfClassroom> slfClassroom = slfClassroomMapper.getSlfClassroom(schoolCoursePages.get(i).getCoursePageId());
				List<String> child_ids = new ArrayList<>();
		//		List<String> vipSlfChildrens = slfChildrenMapper.getChildrensVip();
		//		List<String> courseChildrenIds = slfUserCourseConditionMapper.existsChlidrenId(SchoolCoursePageId);
				//排除该课程存在的
		//		Collection<String> existsvipList=new ArrayList<String>(vipSlfChildrens);
				//去掉未满足开班条件的尊享VIP
		//		existsvipList.removeAll(courseChildrenIds);
				List<SlfChildExpectedTime> models = slfChildExpectedTimeMapper.getSlfChildExpectedTime(SchoolCoursePageId);
			    //客户期盼时间(循环时间段)
				for(int j = 0;j < models.size();j++){
			    	//循环教室
			    	for(int z = 0;z < slfClassroom.size();z++){
			    		map.put("employTime",models.get(j).getExpectedTime());
				    	map.put("classroomId",slfClassroom.get(z).getClassroomId());
				       //查看这个时候教室的占用情况	
				    	String childrenId = models.get(j).getChildrenIds();
				    	String[] childrenIds = childrenId.split(",");
				    	List<String> childrenIdList= Arrays.asList(childrenIds);
				    	Collection<String> existsList=new ArrayList<String>(childrenIdList);
				    	//去掉已经开了班的(安排了课表的小孩)
				    	existsList.removeAll(child_ids);
				    	//根据过滤后的数据进行拼接(当数量大于教室的容纳数量的时候进行操作)
				    	//容纳人数
				    	Integer acceptanceNum = slfClassroom.get(z).getAcceptanceNum();
				    	//接受临时容纳人数
				    	Integer tmAcceptanceNum = slfClassroom.get(z).getTmAcceptanceNum();
				    	//大于了该教室能容纳的最大人数
				    	if(existsList.size()>acceptanceNum + tmAcceptanceNum){
				    	existsList = ((List<String>) existsList).subList(0,acceptanceNum + tmAcceptanceNum);
				    	}
				    	//人数是否满足最低开班人数(满足,直接开班)
				    	if(slfClassroom.get(z).getLeastAcceptanceNum()==null){
				    	slfClassroom.get(z).setLeastAcceptanceNum(0);
				    	}
				    	Integer employ = slfClassroomEmployMapper.IsClassroomEmploy(map);
			    		//未被占用进入此操作(根据时间,排除已占用教室的时间段)
				    	if(employ == 0){
				    	//先判断数量是否满足，再决定生成课表
				    	if(existsList.size()>(slfClassroom.get(z).getLeastAcceptanceNum()-1)){
				    		Integer pNum = 0;
					    	//找到下级包(判断上级包是否完成)
				    		Integer IsUpPages = schoolCoursePageDao.getAloneCoursePagesUpOther(schoolCoursePages.get(i).getParentId());
					    	for(String chIdss : existsList){
					    		map.put("courseBackageId",schoolCoursePages.get(i).getSchoolCoursePageId());
						    	map.put("userId",Integer.parseInt(chIdss));
						    	map.put("parentId",schoolCoursePages.get(i).getParentId());
						    	map.put("coursePageId",schoolCoursePages.get(i).getCoursePageId());
						    	//判断该孩子本课程包是否安排了课程
						    	Integer IsChildrenCourses = slfUserCourseConditionMapper.getIsChildrenCoursePages(map);
						    	//说明该包的下级包有课程
						    	if(IsUpPages>0){
						    	Integer Pagess = schoolCoursePageDao.getAloneCoursePagesUp(map);
						    	//说明已经安排下级课程
						    	if(Pagess>0){
						    	//两种情况(一.安排了未完成;二.安排了已经完成(直接安排课程))	
						    	//找到该下级的schoolCoursePagesId
						    		System.err.println(schoolCoursePages.get(i).getParentId());
						    	Integer courseCount = schoolCourseToPageDaoMapper.getCourseCount(schoolCoursePages.get(i).getParentId());	
						    	Integer finishCount = schoolCoursePageDao.getAloneCoursePagesUpCount(map);
						    	if(courseCount == finishCount && IsChildrenCourses==0){
						    	pNum++;
						    	   }
						    	  }
						    	}else{
						    	if(IsChildrenCourses==0){
						    	pNum++;	
						    	  }
						    	}
					    	}
					    	//直接开班
					    	if(pNum>(slfClassroom.get(z).getLeastAcceptanceNum()-1)){
						    Integer IsUpPage = schoolCoursePageDao.getAloneCoursePagesUpOther(schoolCoursePages.get(i).getParentId());
							String endEmployTime = "";
							Integer emNum = 0;
						    //循环孩子
					    	for(String chIds : existsList){
				    		map.put("courseBackageId",schoolCoursePages.get(i).getSchoolCoursePageId());
					    	map.put("userId",Integer.parseInt(chIds));
					    	map.put("parentId",schoolCoursePages.get(i).getParentId());
					    	map.put("coursePageId",schoolCoursePages.get(i).getCoursePageId());
					    	//判断该孩子本课程包是否安排了课程
					    	Integer IsChildrenCourse = slfUserCourseConditionMapper.getIsChildrenCoursePages(map);
					    	//说明该包的下级包有课程
					    	if(IsUpPage>0){
					    	Integer Pages = schoolCoursePageDao.getAloneCoursePagesUp(map);
					    	//说明已经安排下级课程
					    	if(Pages>0){
					    	//两种情况(一.安排了未完成;二.安排了已经完成(直接安排课程))		
					    	Integer courseCount = schoolCourseToPageDaoMapper.getCourseCount(schoolCoursePages.get(i).getParentId());	
					    	Integer finishCount = schoolCoursePageDao.getAloneCoursePagesUpCount(map);
					    	if(courseCount == finishCount && IsChildrenCourse==0){
					    	//安排课程(多级)排课
					    	String startTime = GetStartTime(models.get(j).getExpectedTime());
					    	//读出所有课程
					    	List<SchoolCourse> schoolCourses = schoolCourseMapper.getPageCourse(schoolCoursePages.get(i).getSchoolCoursePageId());
					    	Integer days = 0; 
					    	for(int y = 0;y < schoolCourses.size();y++){
					    	SlfUserCourseCondition slfUserCourseCondition = new SlfUserCourseCondition();
					    	slfUserCourseCondition.setUserId(Integer.parseInt(chIds));
					    	slfUserCourseCondition.setClassrooomId(slfClassroom.get(z).getClassroomId());
					    	slfUserCourseCondition.setCourseId(schoolCourses.get(y).getCourseId());
					    	slfUserCourseCondition.setCourse(schoolCourses.get(y).getName());
					    	String employTime = DateWay.GetToWeekDate(startTime, days);
					    	endEmployTime = employTime;
					    	slfUserCourseCondition.setEmployTime(employTime);
					    	slfUserCourseCondition.setExpectTime(models.get(j).getExpectedTime());
					    	slfUserCourseCondition.setEmployFlag(0);
					    	slfUserCourseCondition.setFlag(0);
					    	slfUserCourseCondition.setCourseBackageId(schoolCoursePages.get(i).getSchoolCoursePageId());
					    	slfUserCourseCondition.setUserName(myCoursePageMapper.getchildrenName(Integer.parseInt(chIds)));
					    	slfUserCourseCondition.setClassroomName(slfClassroom.get(z).getName());
					    	String schoolId = slfClassroom.get(z).getSchoolId().toString();
					    	slfUserCourseCondition.setSchoolId(schoolId);
					    	slfUserCourseCondition.setCourseType(1);
					    	slfUserCourseConditionMapper.insertSelective(slfUserCourseCondition);
					    	days = days + 7;
					    	}
					    	//不包含的时候加入该排除集合,排除以排班用户重复排班
					        if(!child_ids.contains(chIds)){
					        	child_ids.add(chIds);
					        	emNum++;
					        	SlfChildExpectedTime slfChildExpectedTime = new SlfChildExpectedTime();
						    	slfChildExpectedTime.setFlag(1);
						    	slfChildExpectedTime.setEndTime(endEmployTime);
						    	slfChildExpectedTime.setChildrenId(Integer.parseInt(chIds));
						    	slfChildExpectedTime.setExpectedTime(models.get(j).getExpectedTime());
						    	slfChildExpectedTimeMapper.updateByPrimaryKeySelective(slfChildExpectedTime);
					    	  }
					    	 }
					    	}
					    	}else{
					    	//无下级课程包,直接安排课程(判断课程完成情况或者是是否安排课程)
					    	if(IsChildrenCourse == 0){
					    	//未安排,直接安排课程(一级)排课
				    		//安排课程(多级)排课
					    	String startTime = GetStartTime(models.get(j).getExpectedTime());
					    	//读出所有课程
					    	List<SchoolCourse> schoolCourses = schoolCourseMapper.getPageCourse(schoolCoursePages.get(i).getSchoolCoursePageId());
					    	Integer days = 0; 
					    	for(int y = 0;y < schoolCourses.size();y++){
					    	boolean a = CommonUtil.isEmpty(schoolCourses.get(y));
					    	if(a == false){
					    	SlfUserCourseCondition slfUserCourseCondition = new SlfUserCourseCondition();
					    	slfUserCourseCondition.setUserId(Integer.parseInt(chIds));
					    	slfUserCourseCondition.setClassrooomId(slfClassroom.get(z).getClassroomId());
					    	slfUserCourseCondition.setCourseId(schoolCourses.get(y).getCourseId());
					    	slfUserCourseCondition.setCourse(schoolCourses.get(y).getName());
					    	String employTime = DateWay.GetToWeekDate(startTime, days);
					    	endEmployTime = employTime;
					    	slfUserCourseCondition.setEmployTime(employTime);
					    	slfUserCourseCondition.setExpectTime(models.get(j).getExpectedTime());
					    	slfUserCourseCondition.setEmployFlag(0);
					    	slfUserCourseCondition.setFlag(0);
					    	slfUserCourseCondition.setUserName(myCoursePageMapper.getchildrenName(Integer.parseInt(chIds)));
					    	slfUserCourseCondition.setClassroomName(slfClassroom.get(z).getName());
					    	String schoolId = slfClassroom.get(z).getSchoolId().toString();
					    	slfUserCourseCondition.setSchoolId(schoolId);
					    	slfUserCourseCondition.setCourseBackageId(schoolCoursePages.get(i).getSchoolCoursePageId());
					    	slfUserCourseCondition.setCourseType(1);
					    	slfUserCourseConditionMapper.insertSelective(slfUserCourseCondition);
					    	days = days + 7;
					    	  }
					    	}
					    	//不包含的时候加入该排除集合,排除以排班用户重复排班
					        if(!child_ids.contains(chIds)){
					        child_ids.add(chIds);
					        emNum++;
					        SlfChildExpectedTime slfChildExpectedTime = new SlfChildExpectedTime();
					    	slfChildExpectedTime.setFlag(1);
					    	slfChildExpectedTime.setEndTime(endEmployTime);
					    	slfChildExpectedTime.setChildrenId(Integer.parseInt(chIds));
					    	slfChildExpectedTime.setExpectedTime(models.get(j).getExpectedTime());
					    	slfChildExpectedTimeMapper.updateByPrimaryKeySelective(slfChildExpectedTime);
					    	 }
					    	 }
					       }
				    	}
					    	//教室占用成功
					    	if(emNum>0 && !"".equals(endEmployTime)){
					        SlfClassroomEmploy SlfClassroomEmploys = slfClassroomEmployMapper.IsClassroomEmployMessage(map);
					    	SlfClassroomEmploy slfClassroomEmploy = new SlfClassroomEmploy();
							//该教室已经存在,只是已经是空置状态
					    	if(SlfClassroomEmploys != null){
					    	slfClassroomEmploy.setEmployNum((slfClassroom.get(z).getTmAcceptanceNum()+slfClassroom.get(z).getAcceptanceNum())-emNum);
					    	slfClassroomEmploy.setEndTime(endEmployTime);
					    	slfClassroomEmploy.setFlag(1);
					    	slfClassroomEmploy.setEmployId(SlfClassroomEmploys.getEmployId());
					    	slfClassroomEmployMapper.updateByPrimaryKeySelective(slfClassroomEmploy);
					    	}else{
				    		//判断是否	
					    	slfClassroomEmploy.setClassroomId(slfClassroom.get(z).getClassroomId());
					    	slfClassroomEmploy.setEndTime(endEmployTime);
					    	slfClassroomEmploy.setEmployNum((slfClassroom.get(z).getTmAcceptanceNum()+slfClassroom.get(z).getAcceptanceNum())-emNum);
					    	slfClassroomEmploy.setEmployTime(models.get(j).getExpectedTime());
					    	slfClassroomEmploy.setFlag(1);
					    	slfClassroomEmploy.setType(slfClassroom.get(z).getType());
					    	slfClassroomEmployMapper.insertSelective(slfClassroomEmploy);	
					    	  }
					    	}
					    	}
					    	//(不满足开班条件,顶人数看是否能开班)
					    	}else{
					    	System.err.println("不满足开班人数条件");	
					    	}
					    //教室已被占用
				    	}else{
				    		System.err.println("教室已被占用");
				    	}
				    	}
			    	}
			}
			return "succ";
		}
			
			
	  /**
	    * 已经预约后的C类包用户筛选填充(C排课)
	    */ 
		// @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行一次
		// @Scheduled(cron = "0/15 * * * * *") 
		@RequestMapping("/teachingSchedule")
		@Transactional
	    public void teachingSchedule(){
			   //取出所有未被占完的班级
			   List<SlfClassroomEmploy> SlfClassroomEmploys = slfClassroomEmployMapper.getclassroomEmploys();
			   Map<String,Object> map = new HashMap<String, Object>();
			   for(int i = 0;i < SlfClassroomEmploys.size();i++){
				   Integer pd = 0;
				   map.put("classrooomId", SlfClassroomEmploys.get(i).getClassroomId());
				   map.put("classroomId",SlfClassroomEmploys.get(i).getClassroomId());
				   map.put("expectTime",SlfClassroomEmploys.get(i).getEmployTime());
				   List<SlfChildExpectedTime> childrens = slfChildExpectedTimeMapper.getSlfChildCtype( SlfClassroomEmploys.get(i).getEmployTime());
				   List<SlfUserCourseCondition> slfUserCourseConditions = new ArrayList<SlfUserCourseCondition>();
				   for(int z = 0 ;z<childrens.size();z++){
				   //多少符合这个教室课程条件的小孩
				   map.put("temporaryCtypeChildrenId",childrens.get(z).getChildrenId());
				   map.put("childrenId",childrens.get(z).getChildrenId());
				   map.put("courseId", childrens.get(z).getCouresId());
				   SlfUserCourseCondition slfUserCourseCondition = slfUserCourseConditionMapper.IsexistsCourse(map);
					//这个时间段这个被占用的教室(班级)有该课程
				   if(slfUserCourseCondition!=null){
					   String endTime = slfUserCourseConditionMapper.getChangeClassEmployTimeBk(map);
					      map.put("endTime",endTime);
						  Integer number = slfClassroomEmployMapper.getClassCoursePeopleNumber(map);
						  if(SlfClassroomEmploys.get(i).getEmployNum()+number>0){
							  pd++;
					    	  slfUserCourseConditions.add(slfUserCourseCondition);
						  }
					    }
				   }
				   if(pd>0){
				   if(SlfClassroomEmploys.get(i).getEmployNum()>pd){
					   for(int j = 0;j < slfUserCourseConditions.size();j++){
						   long id = slfUserCourseConditions.get(j).getId();
						   Integer courseId = slfUserCourseConditions.get(j).getCourseId();
						   map.put("courseId",courseId);
						   map.put("userId",slfUserCourseConditions.get(j).getUserId());
						   slfUserCourseConditionMapper.insertEmployChildrenTextC(map);
						   slfUserCourseConditionMapper.deleteEmployChildrenTextC((int)id);
						   map.put("courseNumber",1);
						   map.put("childrenId",slfUserCourseConditions.get(j).getUserId());
						   map.put("flag",2);
						   slfClassCourseNumberMapper.insertSelectiveMap(map);
						   SlfChildExpectedTime slfChildExpectedTime = new SlfChildExpectedTime();
						   slfChildExpectedTime.setChildrenId(slfUserCourseConditions.get(j).getUserId());
						   slfChildExpectedTime.setEndTime(map.get("endTime").toString());
						   slfChildExpectedTime.setFlag(1);
						   slfChildExpectedTime.setExpectedTime(map.get("expectTime").toString());
						   slfChildExpectedTimeMapper.updateByPrimaryKeySelective(slfChildExpectedTime);
					   }
				     }else{
				    	 slfUserCourseConditions = (slfUserCourseConditions).subList(0,pd); 
				       for(int j = 0;j < slfUserCourseConditions.size();j++){
				    	   long id = slfUserCourseConditions.get(j).getId();
				    	   map.put("courseId",slfUserCourseConditions.get(j).getCourseId());
						   map.put("userId",slfUserCourseConditions.get(j).getUserId());
						   slfUserCourseConditionMapper.insertEmployChildrenTextC(map);
						   slfUserCourseConditionMapper.deleteEmployChildrenTextC((int)id);
						   map.put("courseNumber",1);
						   map.put("childrenId",slfUserCourseConditions.get(j).getUserId());
						   map.put("flag",2);
						   slfClassCourseNumberMapper.insertSelectiveMap(map);
						   SlfChildExpectedTime slfChildExpectedTime = new SlfChildExpectedTime();
						   slfChildExpectedTime.setChildrenId(slfUserCourseConditions.get(j).getUserId());
						   slfChildExpectedTime.setEndTime(map.get("endTime").toString());
						   slfChildExpectedTime.setFlag(1);
						   slfChildExpectedTime.setExpectedTime(map.get("expectTime").toString());
						   slfChildExpectedTimeMapper.updateByPrimaryKeySelective(slfChildExpectedTime);
				    	 }
				   }
				     }
				     }
			   }
		   /**
		    * 排C类用户(定时,空闲教室)
		    */ 
//		   @Scheduled(cron = "0 45 0 1/3 * ?")//每3凌晨12:45执行点执行一次*空闲时的定时
		   @RequestMapping("/teachingScheduleOther")
		   @Transactional
		    public String teachingScheduleOther() throws ParseException{
			   //找到所有的教室
			    String Time = DateWay.GetTime();
			    Integer b = myCoursePageMapper.IsMakeLesson(Time);
			    if(b>0){
				   return "fail";
			    }
			   String timeAll = DateWay.TimeAll();
		//	 String Time = "2018-06-09";
		//	   String TimeTwo = "2018-06-10";
		// TimeThree = "2018-06-11";
			   String TimeTwo = DateWay.GetNextTime(1);
			   String TimeThree = DateWay.GetNextTime(2);
			   List<String> listOne = Packaging(Time);
			   List<String> listTwo = Packaging(TimeTwo);
			   List<String> listThree = Packaging(TimeThree);
			   listOne.addAll(listTwo);
			   listOne.addAll(listThree);
			   List<SchoolCoursePage> schoolCoursePage = schoolCoursePageDao.getAloneCoursePagesCtypeAll(timeAll,DateWay.GetNextTimeAll(2));
			   List<SchoolCoursePage> schoolCoursePageList = new ArrayList<SchoolCoursePage>();
			   schoolCoursePageList.addAll(schoolCoursePage);
			   //listOne.removeAll(employList);
			   Map<String,Object> map = new HashMap<String,Object>();
			   List<SlfClassroom> slfClassroom = slfClassroomMapper.getSlfClassrooms();
			   Integer a = 0;
			   for(int i = 0;i < slfClassroom.size();i++){
			  
		       for(String list : listOne){
			   String timeb = list.substring(11,list.length());	  
			   String timea = list.substring(0,10);	   
			   Integer week = DateWay.getDayofweek(timea);
			   String wk = WeekDay(week);
			   timeb = wk + "," + timeb;
			   String startTime = list.substring(0,list.length()-6);
			   startTime += ":00";
			   String endTime = DateWay.addDate(startTime,1);//加1小时方法 
			   map.put("employTime",timeb);
			   map.put("classroomId",slfClassroom.get(i).getClassroomId());
			   SlfClassroomEmploy slfEm = slfClassroomEmployMapper.IsClassroomEmployMessageC(map);
			   if(slfEm==null){
			   Integer courseId = 0;
			   String courseName = null;
		   	   for(int j = 0;j < schoolCoursePageList.size();j++){
		   	   courseId = schoolCoursePageList.get(j).getCoursePageId();
		   	   courseName = schoolCoursePageList.get(j).getName();
		   	   break;
		   	   }
		   	   map.put("courseId",courseId);
		   	   map.put("courseTime",list);
		   	   map.put("classroomId",slfClassroom.get(i).getClassroomId());
		   	   map.put("classroomName",slfClassroom.get(i).getName());
		   	   map.put("courseName",courseName);
		   	   map.put("sequence",a);
		       map.put("courseStartTime",startTime);
		       map.put("schoolId",slfClassroom.get(i).getSchoolId());
		       map.put("endTime",endTime);
		   	   map.put("classroomNumber",slfClassroom.get(i).getAcceptanceNum()+slfClassroom.get(i).getTmAcceptanceNum());
		       schoolCoursePageList.remove(0);
		       myCoursePageMapper.insertPk(map);
			   //增加操作
			   if(0 == schoolCoursePageList.size()){
			   a++;
			   schoolCoursePageList.addAll(schoolCoursePage);
			   }
				 }
		//	   break;
			    }//时间
			   }//教室
			   return "succ";
		  }
		   private String WeekDay(Integer weekDay){
			   String week = "";
			   if(weekDay == 1){
				   week = "周天";
			   }else if(weekDay == 7){
				   week = "周六";
			   }else if(weekDay == 6){
				   week = "周五";
			   }else if(weekDay == 5){
				   week = "周四";
			   }else if(weekDay == 4){
				   week = "周三";
			   }else if(weekDay == 3){
				   week = "周二";
			   }else if(weekDay == 2){
				   week = "周一";
			   }
			return week;
			 }
	   Integer gourp = 0;
	   //组装数据
	   private List<String> Packaging(String Time){
		   List<String> list = new ArrayList<String>();
		   String[] timeSections = Const.TIMESECTION;
		   for(String timeSection : timeSections){
			   list.add(Time+" "+timeSection);
		   }
		return list;
	   }
	   //找到该时间段的开始时间
	   private String GetStartTime(String date){
		   String Time = DateWay.GetTime();
		   String hour = "";
		   String weekString = "";
	       hour = date.substring(date.indexOf(",")+1,date.length());
	       hour = hour.substring(6,8);
	       weekString = date.substring(0,date.indexOf(","));
		   Integer weekDay = DateWay.getDayofweek(Time);
		   //1是星期日、2是星期一、3是星期二、4是星期三、5是星期四、6是星期五、7是星期六 
		   if(weekDay == 1){
			   weekDay = 7;
		   }else if(weekDay == 7){
			   weekDay = 6;
		   }else if(weekDay == 6){
			   weekDay = 5;
		   }else if(weekDay == 5){
			   weekDay = 4;
		   }else if(weekDay == 4){
			   weekDay = 3;
		   }else if(weekDay == 3){
			   weekDay = 2;
		   }else if(weekDay == 2){
			   weekDay = 1;
		   }
		   Integer compWeek = 0;
		   if(weekString.contains("周一")){
			   compWeek = 1; 
		   }else if(weekString.contains("周二")){
			   compWeek = 2; 
		   }else if(weekString.contains("周三")){
			   compWeek = 3; 
		   }else if(weekString.contains("周四")){
			   compWeek = 4; 
		   }else if(weekString.contains("周五")){
			   compWeek = 5; 
		   }else if(weekString.contains("周六")){
			   compWeek = 6; 
		   }else if(weekString.contains("周日")){
			   compWeek = 7; 
		   }
		   Integer compare = weekDay - compWeek;
		   String str = DateWay.GetTimeOther(); 
		   //从下周开始排
		   if(compare > -1){
		   Integer a = 7 - compare;
		   String relutDate = DateWay.GetCal(str,a);
		   relutDate = relutDate.replaceAll("/","-");
		   return relutDate + " "+hour+ ":00:00";
		   //从这周开始排   
		   }else{
		   Integer a = compWeek - weekDay; 
		   String relutDate = DateWay.GetCal(str,a);
		   relutDate = relutDate.replaceAll("/","-");
		   return relutDate + " "+hour+ ":00:00";
		   }
	   }
		//递归找长度
	private Integer Getpackaging(Integer parent_id) {
			//无上级课程包(return 1)
		    if (parent_id > 0){
		    SchoolCoursePage schoolCoursePage = schoolCoursePageDao.getAloneCoursePagesNext(parent_id);
		    ranks++;
		    if(schoolCoursePage==null){
		    Getpackaging(0);
		    }else{
	    	if(schoolCoursePage.getParentId()==null){
	    	schoolCoursePage.setParentId(0);
	    	}
		    Getpackaging(schoolCoursePage.getParentId());
		    }
			}else{
			if(ranks==0){
				return 0;
			}else{
				return ranks;
			 }
			}
			return ranks;
		}
	   //每小时执行一次
	   @RequestMapping("/updateChildrenState")
	   @Scheduled(cron = "0 */60 * * * ?") 
	 //@Scheduled(cron = "0/30 * * * * *") 
	   @Transactional
	   public void updateCourses(){
		   String nowTime = DateWay.TimeAll();
		   //更新已占用教室，大于该时刻的系统时间(更新)
		   slfClassroomEmployMapper.updateClassroomEmploy(nowTime);
		   //修改状态
		   slfChildExpectedTimeMapper.updateEmployExpectedTimeFlag(nowTime);
		   //购买主题课的使用情况(c类Flag全部改成5缺课状态)
		   myCoursePageMapper.updateTextC(nowTime);
		   /*List<SlfUserCourseCondition> slfUserCourseCondition = slfUserCourseConditionMapper.courseFlagOnrOrFour(nowTime);
		   Map<String,Object> map = new HashMap<String, Object>();
		   for(int i = 0;i < slfUserCourseCondition.size();i++){
			   map.put("coursePageId",slfUserCourseCondition.get(i).getCourseId());
			   map.put("childrenId",slfUserCourseCondition.get(i).getUserId());
			   myCoursePageMapper.updateFlag(map);
		   }*/
		   //改变孩子课程信息(缺课)
		   slfUserCourseConditionMapper.updateCourseFlag(nowTime);
	   }
	   /**
	    * 换班级(定时)
	    */ 
	 //@Scheduled(cron = "0 */60 * * * ?") 
	 //@Scheduled(cron = "0/30 * * * * *")
	   @RequestMapping("/changeClassroom")
	   @Transactional
	   public void changeClassroom(){
		   //找到今天是周几
		   String weekDay = GetWeekDay();
		   //周期时间分组
		   List<SlfClassroomEmploy> slfClassroomEmploys = slfClassroomEmployMapper.groupClassroomEmploy(weekDay);
		   for(int i = 0;i < slfClassroomEmploys.size();i++){
			   String slfClassroomEmployId = slfClassroomEmploys.get(i).getClassroomIds();
			   String slfClassroomEmployTime = slfClassroomEmploys.get(i).getEmployTime();
			   String[] ClassroomIds = slfClassroomEmployId.split(",");
			   if(ClassroomIds.length>1){
				   List<String> ClassroomIdLists = Arrays.asList(ClassroomIds);
				   ChangeClassroom(ClassroomIdLists,slfClassroomEmployTime);
			   }
		   }
	   }
	   private String GetWeekDay(){
		   String Time = DateWay.GetTime();
		   Integer weekDay = DateWay.getDayofweek(Time);
		   String week_day = "";
		   //1是星期日、2是星期一、3是星期二、4是星期三、5是星期四、6是星期五、7是星期六 
		   if(weekDay == 1){
			   week_day = "周日";
		   }else if(weekDay == 7){
			   week_day = "周六";
		   }else if(weekDay == 6){
			   week_day = "周五";
		   }else if(weekDay == 5){
			   week_day = "周四";
		   }else if(weekDay == 4){
			   week_day = "周三";
		   }else if(weekDay == 3){
			   week_day = "周二";
		   }else if(weekDay == 2){
			   week_day = "周一";
		   }
		return week_day;
	   }
	   private void ChangeClassroom(List<String> ClassroomLists,String slfClassroomEmployTime){
		   //截取集合初始化
		   List<String> classroom = new ArrayList<String>();
		   List<String> classrooms = new ArrayList<String>();
		   Map<String,Object> map = new HashMap<String,Object>();
		   map.put("employTime",slfClassroomEmployTime);
		   if(ClassroomLists.size()>1){
			   //单数(不会遇到为0的情况)
			   //打乱排序,防止每一次换的班级都是一样
			   Collections.shuffle(ClassroomLists);
	           //双数(可能会遇到为0的情况) 
	    	   classroom = ((List<String>) ClassroomLists).subList(0,2);
	    	   String[] ClassroomArray = ClassroomLists.toArray(new String[classroom.size()]);
	    	   //互换教室的两个ClssroomId
	    	   String classOne = ClassroomArray[0];
	    	   String classTwo = ClassroomArray[1];
	    	   //找到该教室正在学习的这些人的课程
	    	   List<Integer> idsOne = slfUserCourseConditionMapper.getUserCourseConditionIdMapper(Integer.parseInt(classOne));
	    	   List<Integer> idsTwo = slfUserCourseConditionMapper.getUserCourseConditionIdMapper(Integer.parseInt(classTwo));
	    	   map.put("list", idsOne);
	    	   map.put("classroomId",Integer.parseInt(classTwo));
	    	   slfUserCourseConditionMapper.updateUserCourseConditionMapper(map);
	    	   map.put("list", idsTwo);
	    	   map.put("classroomId",Integer.parseInt(classOne));
	    	   slfUserCourseConditionMapper.updateUserCourseConditionMapper(map);
	    	   Integer employOne = slfClassroomEmployMapper.EmployId(map);
	    	   //employOne
	    	   map.put("employId",employOne);
	    	   map.put("classroomId",Integer.parseInt(classTwo));
	    	   Integer employTwo = slfClassroomEmployMapper.EmployId(map);
	    	   slfClassroomEmployMapper.changeClassroom(map);
	    	   //employOne
	    	   map.put("employId",employTwo);
	    	   map.put("classroomId",Integer.parseInt(classOne));
	    	   slfClassroomEmployMapper.changeClassroom(map);
	    	   classrooms.addAll(ClassroomLists);
	    	   List<String> list1= Arrays.asList(ClassroomArray);
	    	   for(int i = 0;i < list1.size();i++){
	    		   classrooms.remove(list1.get(i));
	    	   }
	    	   ChangeClassroom(classrooms,slfClassroomEmployTime);
		   }
	   }
	   /**
	    * 定时安排补课(每天半夜12:30执行一次)
	    * 
	    */
	//   @Scheduled(cron = "0 30 0 * * ?")
	   @RequestMapping("/makeLessonAgain")
	   @Transactional
	   public String makeLessonAgain(){
		  Map<String,Object> map = new HashMap<String,Object>();
		  //找到所有的教室
		  List<SlfClassroom> slfClassroom = slfClassroomMapper.getSlfClassrooms();
		  for(int z = 0;z < slfClassroom.size();z++){
		  //读出所有班级的需要安排补课的人
		  List<SlfUserCourseCondition> slfUserCourseConditions =  slfUserCourseConditionMapper.getNeedLessonAgainPeople();
		  for(int i = 0;i < slfUserCourseConditions.size();i++){
			  map.put("oldClassroomId",slfUserCourseConditions.get(i).getClassrooomId());
			  map.put("oldExpectTime", slfUserCourseConditions.get(i).getExpectTime());
			  //三个筛选条件
			  map.put("childrenId",slfUserCourseConditions.get(i).getUserId());
			  map.put("classroomId", slfClassroom.get(z).getClassroomId());
			  map.put("courseId",slfUserCourseConditions.get(i).getCourseId());
			  map.put("userId",slfUserCourseConditions.get(i).getUserId());
			  //找到复核该人课程的教室
			  List<SlfClassroomEmploy> slfClassroomEmploys = slfClassroomEmployMapper.getCheckClassroomBk(map);
			  Collections.shuffle(slfClassroomEmploys);
			  for(int j = 0;j < slfClassroomEmploys.size();j++){
				  map.put("classroomId",slfClassroomEmploys.get(j).getClassroomId());
				  //排除掉初排期望时间
				  if(!slfClassroomEmploys.get(j).getEmployTime().equals(slfUserCourseConditions.get(i).getExpectTime())){
					  map.put("expectTime",slfClassroomEmploys.get(j).getEmployTime());
					  map.put("endTime",slfUserCourseConditionMapper.getChangeClassEmployTimeBk(map));
					  Integer number = slfClassroomEmployMapper.getClassCoursePeopleNumber(map);
					  //符合条件的班级才能添加人数进来
					  if(slfClassroomEmploys.get(j).getEmployNum()+number>0){
						  //修改原时间课程状态
					//	  slfUserCourseConditionMapper.updateFlagBk(map);
						  //增加一条数据(相当于插班生,但状态是补课)
						  Integer id = slfUserCourseConditionMapper.IsFlagBk(map);
						  //该孩子的课程已经有过一次补课
						  if(id != null && !"".equals(id)){
						  map.put("id", id);
						  //更新补课状态
						  slfUserCourseConditionMapper.updateChangeClassBk(map);
						  map.put("courseNumber",1);
						  map.put("flag",1);
						  slfClassCourseNumberMapper.insertSelectiveMap(map);
					    /*map.put("classroomId",slfUserCourseConditions.get(i).getClassrooomId());
						  map.put("expectTime", slfUserCourseConditions.get(i).getExpectTime());
						  map.put("endTime",slfUserCourseConditionMapper.getChangeClassEmployTimeBk(map));
						  map.put("courseNumber",-1);
						  map.put("flag",1);
						  slfClassCourseNumberMapper.insertSelectiveMap(map);*/
						  }else{
						  //新增补课(插入一条数据)	  
						  SlfUserCourseCondition slfUserCourseCondition = new SlfUserCourseCondition();
						  slfUserCourseCondition.setUserId(slfUserCourseConditions.get(i).getUserId());
						  slfUserCourseCondition.setClassrooomId(slfClassroomEmploys.get(j).getClassroomId());
						  slfUserCourseCondition.setCourse(slfUserCourseConditions.get(i).getCourse());
						  slfUserCourseCondition.setCourseId(slfUserCourseConditions.get(i).getCourseId());
						  slfUserCourseCondition.setEmployTime(slfUserCourseConditionMapper.getChangeClassEmployTimeBk(map));
						  slfUserCourseCondition.setExpectTime(slfClassroomEmploys.get(j).getEmployTime());
						  //插班生处理(Flag=1)
						  slfUserCourseCondition.setUserName(slfUserCourseConditions.get(i).getUserName());
						  slfUserCourseCondition.setSchoolId(slfUserCourseConditions.get(i).getSchoolId());
						  slfUserCourseCondition.setClassroomName(slfClassroomMapper.getClassroomName(slfClassroomEmploys.get(j).getClassroomId()));
						  slfUserCourseCondition.setFlag(0);
						  slfUserCourseCondition.setCourseType(1);
						  slfUserCourseCondition.setEmployFlag(2);
						  slfUserCourseCondition.setCourseBackageId(slfUserCourseConditions.get(i).getCourseBackageId());
						  slfUserCourseConditionMapper.insertSelective(slfUserCourseCondition);
						  map.put("courseNumber",1);
						  map.put("flag",1);
						  slfClassCourseNumberMapper.insertSelectiveMap(map);
						  }
						  //修改flag
						  SlfUserCourseCondition slfUserCourseCondition = new SlfUserCourseCondition();
						  slfUserCourseCondition.setId(slfUserCourseConditions.get(i).getId());
						  slfUserCourseCondition.setFlag(4);
						  slfUserCourseConditionMapper.updateByPrimaryKeySelective(slfUserCourseCondition);
						  break;
					  }
				  }
			  }
		  }
	   }
		  return "succ";
	   }
	   /**
	     * 查询所有课程情况
	     * @param classroomId
	     * @param ajaxRes
	     * @return
	     */
		@RequestMapping("/getSchoolPackageAll")
	   public AjaxRes getSchoolPackageAll(AjaxRes ajaxRes,Integer classroomId){
		   try{
			   List<SchoolCoursePage> SchoolCoursePages = schoolCoursePageDao.getSchoolCoursePages(classroomId);
				ajaxRes.setSucceed(SchoolCoursePages,Const.DATA_SUCCEED);
			} catch (Exception e) {
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
	   }
		/**
	     * c类课程的呈现
	     * @param 
	     * @param ajaxRes
	     * @return
	     */
		@RequestMapping("/getSchoolCourseCourseLoginC")
		public AjaxRes GetSchoolCourseCourseC(AjaxRes ajaxRes,HttpServletResponse resp,HttpServletRequest req){
			try {
			    Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
			    Map<String,Object> map = new HashMap<String, Object>();
			    map.put("userId",childrenId);
			//	Integer childrenId = 180;
			    List<SlfMyCoursePage> SchoolCoursePagePay = myCoursePageMapper.getAloneCoursePagesCtypePay(childrenId);
			    //查询时间
			    for(int i = 0;i < SchoolCoursePagePay.size();i++){
			    	map.put("courseId",SchoolCoursePagePay.get(i).getCoursePageId());
			    	SlfUserCourseCondition slfUserCourseCondition = slfUserCourseConditionMapper.IsStartsWeek(map);
			    	if(slfUserCourseCondition != null){
			    	DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
			    	DateTime t2 = DateTime.parse(slfUserCourseCondition.getEmployTime().toString(), format).minusHours(1);
			    	DateTime t1=new DateTime();
			    	Duration duration=new Duration(t1,t2);
	    		    Long countDown =duration.getStandardSeconds();
	    		    SchoolCoursePagePay.get(i).setDownCount(countDown);
	    		    String SdateStr = new SimpleDateFormat("yyyy-MM-dd").format(SchoolCoursePagePay.get(i).getSalesStartDate());
	    		    String EdateStr = new SimpleDateFormat("yyyy-MM-dd").format(SchoolCoursePagePay.get(i).getSalesEndDate());
	    		    SchoolCoursePagePay.get(i).getSalesEndDate();
	    		    SchoolCoursePagePay.get(i).setSalesStartDateString(SdateStr);
	    		    SchoolCoursePagePay.get(i).setSalesEndDateString(EdateStr);
	    		    SchoolCoursePagePay.get(i).setClassName(slfUserCourseCondition.getClassroomName());
			        }else{
	    		    String SdateStr = new SimpleDateFormat("yyyy-MM-dd").format(SchoolCoursePagePay.get(i).getSalesStartDate());
	    		    String EdateStr = new SimpleDateFormat("yyyy-MM-dd").format(SchoolCoursePagePay.get(i).getSalesEndDate());
	    		    SchoolCoursePagePay.get(i).getSalesEndDate();
	    		    SchoolCoursePagePay.get(i).setSalesStartDateString(SdateStr);
	    		    SchoolCoursePagePay.get(i).setSalesEndDateString(EdateStr);
	    		    SchoolCoursePagePay.get(i).setClassName(ThreadLocalUtil. getChildren().getSchoolName());
			       }
			    }
				List<SchoolCoursePage> schoolCoursePage = schoolCoursePageDao.getAloneCoursePagesCtype(childrenId);
				for(int i = 0;i < schoolCoursePage.size();i++){
					SimpleDateFormat format1 =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
					String SdateStr = new SimpleDateFormat("yyyy-MM-dd").format(schoolCoursePage.get(i).getSalesStartDate());
	    		    String EdateStr = new SimpleDateFormat("yyyy-MM-dd").format(schoolCoursePage.get(i).getSalesEndDate());
	    		  /*  Date staertDate = format1.parse(SdateStr);
	    		    Date endDate = format1.parse(EdateStr);*/
	    		    schoolCoursePage.get(i).setSalesStartDateString(SdateStr);
	    		    schoolCoursePage.get(i).setSalesEndDateString(EdateStr);
	    		    schoolCoursePage.get(i).setClassName(ThreadLocalUtil. getChildren().getSchoolName());
				}
				//在课B类推荐
				List<SlfUserCourseCondition> pages = slfUserCourseConditionMapper.getClasslesssonPage();
				//打乱
				Collections.shuffle(pages);
				if(pages.size()>1){
					pages = ((List<SlfUserCourseCondition>) pages).subList(0,2);
				}else {
					pages = ((List<SlfUserCourseCondition>) pages).subList(0,pages.size());
				}
				List<AloneCourse> pagesB = new ArrayList<AloneCourse>();
                for(int j = 0;j < pages.size();j++){
                	AloneCourse aloneCourse = aloneCourseDao.getCourses(pages.get(j).getCourseId());
                	DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
			    	DateTime t2 = DateTime.parse(pages.get(j).getEmployTime().toString(), format).minusHours(1);
			    	DateTime t1=new DateTime();
			    	Duration duration=new Duration(t1,t2);
	    		    Long countDown =duration.getStandardSeconds();
	    		    aloneCourse.setDownCount(countDown);
	    		    aloneCourse.setClassName(pages.get(j).getClassroomName());
	    		    pagesB.add(aloneCourse);
                }
				map.put("pay",SchoolCoursePagePay);		
				map.put("noPay",schoolCoursePage);
				map.put("pagesB",pagesB);
				ajaxRes.setSucceed(map,Const.DATA_SUCCEED);
			} catch (Exception e) {
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}
		
		/**
	     * c类课程的呈现
	     * @param 
	     * @param ajaxRes
	     * @return
	     */
		/*@RequestMapping("/getSchoolCourseCourseNologinC")
		public AjaxRes getSchoolCourseCourseCNologin(AjaxRes ajaxRes,HttpServletResponse resp,HttpServletRequest req){
			try {
				Map<String,Object> map = new HashMap<String, Object>();
		//		List<SchoolCoursePage> schoolCoursePage = schoolCoursePageDao.getAloneCoursePagesCtypeAll();
				for(int i = 0;i < schoolCoursePage.size();i++){
					SimpleDateFormat format1 =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
					String SdateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(schoolCoursePage.get(i).getSalesStartDate());
	    		    String EdateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(schoolCoursePage.get(i).getSalesStartDate());
	    		    schoolCoursePage.get(i).setSalesStartDateString(SdateStr);
	    		    schoolCoursePage.get(i).setSalesEndDateString(EdateStr);
	    		    schoolCoursePage.get(i).setClassName(ThreadLocalUtil. getChildren().getSchoolName());
				}
				for(int i = 0;i < schoolCoursePage.size();i++){
				//	SimpleDateFormat format1 =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
					String SdateStr = new SimpleDateFormat("yyyy-MM-dd").format(schoolCoursePage.get(i).getSalesStartDate());
	    		    String EdateStr = new SimpleDateFormat("yyyy-MM-dd").format(schoolCoursePage.get(i).getSalesEndDate());
	    		    schoolCoursePage.get(i).setSalesStartDateString(SdateStr);
	    		    schoolCoursePage.get(i).setSalesEndDateString(EdateStr);
	    		    schoolCoursePage.get(i).setClassName("请先登录");
				}
				//在课B类推荐
				List<SlfUserCourseCondition> pages = slfUserCourseConditionMapper.getClasslesssonPage();
				//打乱
				Collections.shuffle(pages);
				if(pages.size()>1){
					pages = ((List<SlfUserCourseCondition>) pages).subList(0,2);
					
				}else {
					pages = ((List<SlfUserCourseCondition>) pages).subList(0,pages.size());
				}
				List<AloneCourse> pagesB = new ArrayList<AloneCourse>();
                for(int j = 0;j < pages.size();j++){
            	AloneCourse aloneCourse = aloneCourseDao.getCourses(pages.get(j).getCourseId());
            	DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		    	DateTime t2 = DateTime.parse(pages.get(j).getEmployTime().toString(), format).minusHours(1);
		    	DateTime t1=new DateTime();
		    	Duration duration=new Duration(t1,t2);
    		    Long countDown =duration.getStandardSeconds();
    		    aloneCourse.setDownCount(countDown);
    		    aloneCourse.setClassName(pages.get(j).getClassroomName());
    		    pagesB.add(aloneCourse);
                }
				map.put("noPay",schoolCoursePage);
				map.put("pagesB",pagesB);
				ajaxRes.setSucceed(map,Const.DATA_SUCCEED);
			} catch (Exception e) {
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}*/
		@RequestMapping("/getCourseTheme")
		public AjaxRes getCourseTheme(AjaxRes ajaxRes,String date,HttpServletRequest req){
			try{
		    Assert.notNull(date, String.format(ErrorUtil.PARAMETER_NULL,"时间"));
	//	    String date = "2018-06-02";
	//		String yue =date.substring(date.indexOf("-")+1, date.lastIndexOf("-"));
			/*Integer a = 05;
			Integer.parseInt(yue);*/
			/*if(Integer.parseInt(yue)<10){
				yue = "0"+yue;
				if(yue.length()>1){
					
				}else{
					
				}
			}*/
			/*int one = date.lastIndexOf("-");
			String day = date.substring((one+1),date.length());
		//	String day = date.substring(imgUrl.lastIndexOf("/")+1);
			if(Integer.parseInt(day)<10){
				day = "0"+day;
			}
			String year = date.substring(0,4);
			String newdate = year+"-"+yue+"-"+day;*/
			List<SchoolCoursePage> SchoolCoursePages = schoolCoursePageDao.getCoursetheme(date);
			Map<String,Object> map = new HashMap<String, Object>();
			for(int i = 0;i < SchoolCoursePages.size();i++){
				//	SimpleDateFormat format1 =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
					String SdateStr = new SimpleDateFormat("yyyy-MM-dd").format(SchoolCoursePages.get(i).getSalesStartDate());
	    		    String EdateStr = new SimpleDateFormat("yyyy-MM-dd").format(SchoolCoursePages.get(i).getSalesEndDate());
	    		    SchoolCoursePages.get(i).setSalesStartDateString(SdateStr);
	    		    SchoolCoursePages.get(i).setSalesEndDateString(EdateStr);
	    		    SchoolCoursePages.get(i).setClassName("请先登录");
	    		    Integer b = SchoolCoursePages.get(i).getClassroomNumber();
	    		    map.put("id",SchoolCoursePages.get(i).getId());
	    		    Integer a = myCoursePageMapper.getZjChildrenNumberCount(map);
	    		    SchoolCoursePages.get(i).setSyClassroomNumber(b-a);
				}
			ajaxRes.setSucceed(SchoolCoursePages,Const.DATA_SUCCEED);
			}catch (Exception e) {
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}
		
		@RequestMapping("/getCourseThemeLogin")
		public AjaxRes getCourseThemeLogin(AjaxRes ajaxRes,String date,HttpServletRequest req){
			try{
				Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
		//		Integer userId = ThreadLocalUtil.getUser().getUserId();
		//		Integer childrenId = 180;
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("childrenId",childrenId);
				map.put("courseTime", date);
				//已购买的
				List<SchoolCoursePage> SchoolCoursePages = schoolCoursePageDao.getChildrenCourser(map);
				for(int j = 0;j < SchoolCoursePages.size();j++){
					String datea = SchoolCoursePages.get(j).getCourseTime();
					String Time = datea.substring(0,datea.length()-6);
					Time += ":00";
	            	DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
			    	DateTime t2 = DateTime.parse(Time.toString(), format).minusHours(0);
			    	DateTime t1=new DateTime();
			    	Duration duration=new Duration(t1,t2);
	    		    Long countDown =duration.getStandardSeconds();
	    		    SchoolCoursePages.get(j).setDownCount(countDown);
	    		    //统计
	    		    map.put("id",SchoolCoursePages.get(j).getId());
	    		    Integer a = myCoursePageMapper.getZjChildrenNumberCount(map);
	    		    Integer b = SchoolCoursePages.get(j).getClassroomNumber(); 
	    		    SchoolCoursePages.get(j).setSyClassroomNumber(b-a);
	                }
				//未购买的
				List<SchoolCoursePage> NoSchoolCoursePages = schoolCoursePageDao.getChildrenCourserNo(map);
				for(int i = 0;i < NoSchoolCoursePages.size();i++){
					//	SimpleDateFormat format1 =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
						String SdateStr = new SimpleDateFormat("yyyy-MM-dd").format(NoSchoolCoursePages.get(i).getSalesStartDate());
		    		    String EdateStr = new SimpleDateFormat("yyyy-MM-dd").format(NoSchoolCoursePages.get(i).getSalesEndDate());
		    		    NoSchoolCoursePages.get(i).setSalesStartDateString(SdateStr);
		    		    NoSchoolCoursePages.get(i).setSalesEndDateString(EdateStr);
		    		    String datea = NoSchoolCoursePages.get(i).getCourseTime();
						String Time = datea.substring(0,datea.length()-6);
						Time += ":00";
		            	DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
				    	DateTime t2 = DateTime.parse(Time.toString(), format).minusHours(0);
				    	DateTime t1=new DateTime();
				    	Duration duration=new Duration(t1,t2);
		    		    Long countDown =duration.getStandardSeconds();
		    		    NoSchoolCoursePages.get(i).setDownCount(countDown);
		    		    map.put("id",NoSchoolCoursePages.get(i).getId());
		    		    Integer a = myCoursePageMapper.getZjChildrenNumberCount(map);
		    		    Integer b = NoSchoolCoursePages.get(i).getClassroomNumber(); 
		    		    NoSchoolCoursePages.get(i).setSyClassroomNumber(b-a);
					}
				map.put("Pay",SchoolCoursePages);
				map.put("noPay",NoSchoolCoursePages);
				ajaxRes.setSucceed(map,Const.DATA_SUCCEED);
			}catch (Exception e) {
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}
		//预约
		@RequestMapping("/getCourseThemePay")
		@Transactional
		public AjaxRes getCourseThemePay(AjaxRes ajaxRes,String date,HttpServletRequest req,String id,Integer courseId){
			try{
				//新增预约C类课程 1.新增临时表,扣钱(用户)
				Map<String,Object> map = new HashMap<String,Object>(); 
				Integer userId = ThreadLocalUtil.getUser().getUserId();
			//	Integer childrenId = 180;
			//	Integer userId = 248;
				Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
				Integer zhlfb = myCoursePageMapper.getuserLfb(userId);
				map.put("usersId",userId);
				map.put("childrenId",childrenId);
			    map.put("id",id);
			    Integer pd = schoolCoursePageDao.getChildrenCourserCount(map);
			    if(pd > 0){
		    	//不能重复购买	
				throw new IllegalArgumentException(Const.BUYA_ALEARY);	
			    }
			    Integer totalNumber = myCoursePageMapper.getClassroomNumber(map);
			    Integer alearyNumber = myCoursePageMapper.getZjChildrenNumberCount(map);
			    if(totalNumber!=null){
			    Integer syTotal = totalNumber - alearyNumber;
			    if(syTotal==0){
			    throw new IllegalArgumentException(Const.ALREADY_FULL);
			     }
			    }
				double money = myCoursePageMapper.getdiscountPriceCourse(courseId);
				if(zhlfb < money){
				ajaxRes.setSucceed(Const.FAIL);
				return ajaxRes;
				}
				map.put("courseId", courseId);
				map.put("childrenId", childrenId);
				map.put("id",id);
				Integer a = myCoursePageMapper.Ispipei(map);
				if(a==0){
				ajaxRes.setSucceed(Const.PPFAIL);
				return ajaxRes;	
				}
				myCoursePageMapper.insertMyCoursePageC(map);
				//增加一条数据
				map.put("childrenId",childrenId);
				map.put("bespokePrice",money);
				map.put("isFlag",1);
				map.put("flag",0);
				map.put("courseType",2);
				myCoursePageMapper.insertChildrenMessage(map);
				//扣钱
				map.put("lfb",zhlfb-money);
				myCoursePageMapper.updateLfb(map);
				ajaxRes.setSucceed(Const.SUCC);
			}catch (Exception e) {
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}
		//取消预约
		@RequestMapping("/cancelCourseTheme")
		@Transactional
		public AjaxRes cancelCourseTheme(AjaxRes ajaxRes,HttpServletRequest req,Integer courseId,Integer id,String seconds){
			try{
			 Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
		     Integer userId = ThreadLocalUtil.getUser().getUserId();
		  // Integer userId = 248;
			//找到用户账户立方币
		  	 Integer zhlfb = myCoursePageMapper.getuserLfb(userId);
		  // Integer childrenId = 180;
		     //全局立方比返回值
		  	 Integer lfb = 0;
		  	 //查看是否偶课程
		  	 String day = seconds.substring(0,2);
		     String hours = seconds.substring(3,5);
		     String min = seconds.substring(7,9);
		     String second = seconds.substring(seconds.length()-3,seconds.length()-1);
		     double daySeconds = Integer.parseInt(day)*86400;
		     double hoursSeconds = Integer.parseInt(hours)*3600;
		     double minSeconds = Integer.parseInt(min)*60;
		     double newSeconds = daySeconds+hoursSeconds+minSeconds+Integer.parseInt(second);
			 Map<String,Object> map = new HashMap<String, Object>();
			 map.put("courseId",courseId);
			 map.put("usersId",userId);
			 map.put("userId",childrenId);
			 map.put("coursePageId",courseId);
			 map.put("childrenId",childrenId);
			 //修改
			 map.put("id",id);
			 //找到预约价格
			 double money = myCoursePageMapper.getBespokePrice(map);
			 myCoursePageMapper.cancelCourseTheme(map);
			 //删除购买的课程
			 myCoursePageMapper.updateCourseC(map);
			 //返回钱
			 double hour = newSeconds / 3600;
			 if(hour < 3){
			 double m = (newSeconds % 3600)/60;
			 double moneyDouble = m/60*(double)money;
			 moneyDouble = (double)Math.round(moneyDouble * 100) / 100; 
			 map.put("lfb",(double)zhlfb+moneyDouble);
			 lfb = (int)moneyDouble;
			 }else{
			 map.put("lfb",zhlfb+money);
			 lfb = (int)money;
			 }
			 myCoursePageMapper.updateLfb(map);
			 ajaxRes.setSucceed(lfb);
			}catch(Exception e){
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}
		//判断该孩子是否在该时间段有课程
			@RequestMapping("/beOccupiedCourse")
			@Transactional
			public AjaxRes beOccupiedCourse(AjaxRes ajaxRes,HttpServletRequest req,String seconds,Integer id,Integer courseId){
				try{
			//	Assert.notNull(courseStartTime, String.format(ErrorUtil.PARAMETER_NULL, "开始时间不能为空"));
				Assert.notNull(seconds, String.format(ErrorUtil.PARAMETER_NULL,"倒计时不能为空"));
				//先判断是否小于3个小时
				//查看是否偶课程
				String courseStartTime = myCoursePageMapper.getCourseStartTime(id);
			  	String day = seconds.substring(0,2);
			    String hours = seconds.substring(3,5);
			    String min = seconds.substring(7,9);
			    String second = seconds.substring(seconds.length()-3,seconds.length()-1);
			    double daySeconds = Integer.parseInt(day)*86400;
			    double hoursSeconds = Integer.parseInt(hours)*3600;
			    double minSeconds = Integer.parseInt(min)*60;
			    double newSeconds = daySeconds+hoursSeconds+minSeconds+Integer.parseInt(second);
			    double hour = newSeconds / 3600;
				if(hour < 3.0){
				//时间小于3小时
				throw new IllegalArgumentException(Const.TIME_EXPIRES);		
				}
				//判断是否为尊享
				if(ThreadLocalUtil.getUser()!=null){
				//Integer childrenId = 308;s
				Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
				Integer a = slfChildrenMapper.IsVip(childrenId);
				if(a > 0){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("courseId", courseId);
				map.put("childrenId", childrenId);
				map.put("id",id);
				double money = 0;
				myCoursePageMapper.insertMyCoursePageC(map);
				//增加一条数据
				map.put("childrenId",childrenId);
				map.put("bespokePrice",money);
				map.put("isFlag",1);
				map.put("flag",0);
				map.put("courseType",2);
				myCoursePageMapper.insertChildrenMessage(map);
				throw new IllegalArgumentException(Const.IS_VIP);		
				  } 
				}
				//查询当前娃娃这个时间段是否被占	
				if(ThreadLocalUtil.getUser()==null){
				ajaxRes.setSucceed(Const.SUCC);
				}else{
				Map<String,Object> map = new HashMap<String,Object>();	
				//年月日
				String timeOne = courseStartTime.substring(0,10);
				Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();	
		//		Integer childrenId = 308;	
				Integer week = DateWay.getDayofweek(timeOne);
				String wk = WeekDay(week);
				String startTime = courseStartTime.substring(courseStartTime.length()-8,courseStartTime.length()-3);
			//	startTime += ":00";
				startTime = wk+","+startTime;
				map.put("childrenId",childrenId);
				map.put("expectedTime",startTime);
				map.put("childrenId",childrenId);
			    map.put("id",id);
			    Integer pd = schoolCoursePageDao.getChildrenCourserCount(map);
			    if(pd > 0){
		    	//不能重复购买	
				throw new IllegalArgumentException(Const.BUYA_ALEARY);	
			    }
				Integer Is = slfChildExpectedTimeMapper.IsbeOccupiedCourse(map);
				//未被占用
				if(Is == 0){
				ajaxRes.setSucceed(Const.SUCC);	
				}else{
				//被占用	
				throw new IllegalArgumentException(Const.BEOCCUPIEDCOURES);	
				}
				}
				}catch(Exception e){
					ajaxRes.setFailMsg(e.getMessage());
				}
				return ajaxRes;
			}
		    //查看主题详情
			@RequestMapping("/detailsTheme")
			@Transactional
			public AjaxRes detailsTheme(AjaxRes ajaxRes,HttpServletRequest req,Integer courseId,String seconds,Integer flag,Integer id){
				try{
					List<AloneCoursePage> aloneCoursePage = aloneCoursePageDao.getCouserThemeMassage(courseId);
				    Map<String,Object> map = new HashMap<String, Object>();
				    //00天00小时03分钟51秒
				    if(flag == 1){
				    Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
			    	if(seconds!=null && !"".equals(seconds)){
					seconds = java.net.URLDecoder.decode(seconds, "utf-8");
				    String day = seconds.substring(0,2);
				    String hours = seconds.substring(3,5);
				    String min = seconds.substring(7,9);
				    String second = seconds.substring(seconds.length()-3,seconds.length()-1);
				    double daySeconds = Integer.parseInt(day)*86400;
				    double hoursSeconds = Integer.parseInt(hours)*3600;
				    double minSeconds = Integer.parseInt(min)*60;
				    double newSeconds = daySeconds+hoursSeconds+minSeconds+Integer.parseInt(second);
				    //大于0时可以购买,小于0时不能购买(只能看详情)
				    //将开课(可购买)
				    map.put("childrenId",childrenId);
				    map.put("id",id);
				    if(newSeconds<10801){
				    map.put("seconds","小于三小时");
				    }else{
			    	Integer pd = schoolCoursePageDao.getChildrenCourserCount(map);
				    if(pd == 0){
				    map.put("seconds","可预约");
				    }else{
				    map.put("seconds","已购买");	
				    }
				    }
				    }else{
				    //已完课(无法购买)
				    map.put("seconds","课程已结束");		
				    }
				    //游客(购买跳转)
				    }else{
				    map.put("seconds","游客"); 	
				    }
				    Integer totalNumber = myCoursePageMapper.getClassroomNumber(map);
				    Integer alearyNumber = myCoursePageMapper.getZjChildrenNumberCount(map);
				    if(totalNumber!=null){
				    Integer syTotal = totalNumber - alearyNumber;
				    if(syTotal==0){
				    map.put("seconds","课程已结束"); 	
				     }
				    }
				    map.put("aloneCoursePages",aloneCoursePage);
					ajaxRes.setSucceed(map,Const.DATA_SUCCEED);
				}catch(Exception e){
					ajaxRes.setFailMsg(e.getMessage());
				}
				return ajaxRes;
			}
				
		/**
	     * c类课程(主题预约)取消预约
	     * @param 
	     * @param ajaxRes
	     * @return
	     */
		@RequestMapping("/cancelSchoolCourseCourseC")
		@Transactional
		public AjaxRes cancelSchoolCourseCourseC(AjaxRes ajaxRes,HttpServletRequest req,Integer courseId){
			try{
			//删除购买的课程包(C类):1.第一种情况:未安排课程(直接退钱),删掉购买包,删除临时表里面的数据；2。已安排课程(直接退钱),删除购买包,删除课程安排数据,增加一个空位置出来
			 Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
		     Integer userId = ThreadLocalUtil.getUser().getUserId();
		  // Integer userId = 248;
			//找到用户账户立方币
		  	 Integer zhlfb = myCoursePageMapper.getuserLfb(userId);
		  // Integer childrenId = 180;
		    //查看是否偶课程
			 Map<String,Object> map = new HashMap<String, Object>();
			 map.put("courseId",courseId);
			 map.put("usersId",userId);
			 map.put("userId",childrenId);
			 map.put("coursePageId",courseId);
			 map.put("childrenId",childrenId);
			 Integer id = slfUserCourseConditionMapper.IsExistconditionC(map);	
			 //存在数据
			 if(id != null && !"".equals(id)){
			 myCoursePageMapper.updateCourseC(map);
			 //找到课程condition
			 SlfUserCourseCondition slfUserCourseConditions = slfUserCourseConditionMapper.getCancelUserCourse(map);
			 map.put("courseNumber",-1);
			 map.put("childrenId",childrenId);
			 map.put("classroomId",slfUserCourseConditions.getClassrooomId());
			 map.put("expectTime",slfUserCourseConditions.getExpectTime());
			 map.put("endTime",slfUserCourseConditions.getEmployTime());
			 map.put("flag",2);
			 slfClassCourseNumberMapper.insertSelectiveMap(map);
			 //删除课程
			 slfUserCourseConditionMapper.deleteByPrimaryKey(slfUserCourseConditions.getId());
			 //返回钱
			 Integer a = myCoursePageMapper.discountPrice(map);
			 map.put("lfb",zhlfb+a);
			 myCoursePageMapper.updateLfb(map);
			 }else{
			 //删除购买的课程
			 myCoursePageMapper.updateCourseC(map);
			 //删除临时表里面的数据
			 myCoursePageMapper.deleteCourseTemporaryC(map);
			 //返回钱
			 Integer a = 3;
			 map.put("lfb",zhlfb+a);
			 myCoursePageMapper.updateLfb(map);
			 ajaxRes.setSucceed(Const.SUCC);
			 }
			}catch(Exception e){
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}
		
		/**
	     * c类课程(主题预约)点击预约
	     * @param 
	     * @param ajaxRes
	     * @return
	     */
		@RequestMapping("/insertSchoolCourseCourseC")
		@Transactional
		public AjaxRes insertSchoolCourseCourseC(AjaxRes ajaxRes,HttpServletRequest req,Integer courseId){
			try{
			//新增预约C类课程 1.新增临时表,扣钱(用户)
			Map<String,Object> map = new HashMap<String,Object>(); 
			Integer userId = ThreadLocalUtil.getUser().getUserId();
		//	Integer childrenId = 180;
		//	Integer userId = 248;
			Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
			Integer zhlfb = myCoursePageMapper.getuserLfb(userId);
			map.put("usersId",userId);
			double discountPrice = myCoursePageMapper.getdiscountPriceCourse(courseId);
			if(zhlfb < discountPrice){
				ajaxRes.setSucceed(Const.FAIL);
				return ajaxRes;
			}
			map.put("temporaryCtypeChildrenId",childrenId);
			map.put("temporaryCouresId",courseId);
			map.put("courseId", courseId);
			map.put("childrenId", childrenId);
			slfUserCourseConditionMapper.insertTemporaryStorageTable(map);
			myCoursePageMapper.insertMyCoursePageC(map);
			//扣钱
			map.put("lfb",zhlfb-discountPrice);
			myCoursePageMapper.updateLfb(map);
			ajaxRes.setSucceed(Const.SUCC);
			}catch(Exception e){
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}

	/**
	 * 查询所有课程
	 * @param res
	 * @param date
	 * @return
	 */
		@RequestMapping("/getSlfUserCourseCondition")
	   public AjaxRes getCoursestable(AjaxRes res,String date){
		   try{
			   List<SlfClassroomEmploy> slfClassroomEmploys = new ArrayList<SlfClassroomEmploy>();
				String[]  timeQuantums = Const.TIMESECTION;
				for(String timeQuantum : timeQuantums){
				//先找B,再找C(1B;2C;3无)
			  //String weekTime = wk + "," + timeQuantum;
				String endTime = timeQuantum.substring(timeQuantum.length()-5,timeQuantum.length());
				endTime += ":00";
				endTime = date + " " + endTime;
				SlfClassroomEmploy slfClassroomEmploy = slfClassroomEmployMapper.getIsEmployClassroomMasseage(endTime);	
				if(slfClassroomEmploy == null){
				//判断C类
				String startTime = timeQuantum.substring(0,5);
				startTime += ":00";
				startTime = date + " " + startTime;
				SlfClassroomEmploy ClassroomEmploy = slfClassroomEmployMapper.getIsEmployClassroomCMasseage(startTime);
				if(ClassroomEmploy != null){
				SlfClassroomEmploy ClassroomEmployC = new SlfClassroomEmploy();
				ClassroomEmployC.setEmployTime(timeQuantum);
				ClassroomEmployC.setType(2);
				ClassroomEmployC.setEndTime(ClassroomEmploy.getEndTime());
				slfClassroomEmploys.add(ClassroomEmployC);
				}else{
				SlfClassroomEmploy ClassroomEmployNo = new SlfClassroomEmploy();
				ClassroomEmployNo.setEmployTime(timeQuantum);
				ClassroomEmployNo.setType(3);
				slfClassroomEmploys.add(ClassroomEmployNo);
				}
				}else{
				//被B类课程占用
				SlfClassroomEmploy ClassroomEmployB = new SlfClassroomEmploy();
				ClassroomEmployB.setEndTime(slfClassroomEmploy.getEndTime());
				ClassroomEmployB.setType(1);
				ClassroomEmployB.setEmployTime(timeQuantum);
				slfClassroomEmploys.add(ClassroomEmployB);
				  }
				}
				res.setSucceed(slfClassroomEmploys);
			} catch (Exception e) {
				res.setFailMsg(e.getMessage());
			}
			return res;
	   }
    /**
     * 发送验证码
     * @param phone
     * @param flag
     * @return
     */
	@RequestMapping("/sendIdentifyCode")
	public AjaxRes sendIdentifyCode(@RequestParam("phone") String phone,@RequestParam("flag") String flag, AjaxRes ajaxRes) {
		try {
			this.commonService.sendIdentifyCode(phone,flag);
			ajaxRes.setSucceedMsg(Const.DATA_SUCCEED);
		} catch (Exception e) {
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}

	@RequestMapping("/common/getUserDtoList")
	public AjaxRes getUserDtoList(@RequestParam Map<String, Object> map, AjaxRes ajaxRes) {
		try {
			List<UserDto> userDtos = this.commonService.getUserDtoList(map);
			ajaxRes.setSucceed(userDtos, Const.DATA_SUCCEED);
		} catch (Exception e) {
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}
	@RequestMapping("/getSlfClassroomEmploy")
	public AjaxRes getSlfClassroomEmploy(AjaxRes ajaxRes,SlfClassroomEmploy slfClassroomEmploy){
		try{
			List<SlfClassroomEmploy> slfClassroomEmployList = this.slfClassroomEmployMapper.getSlfClassroomEmploy(slfClassroomEmploy);
			ajaxRes.setSucceed(slfClassroomEmployList,Const.DATA_SUCCEED);
		}catch (Exception e){
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}
	@RequestMapping("/insertClassroomPackage")
	public AjaxRes insertClassroomPackage(AjaxRes ajaxRes,Integer classroomId,String coursePackageIds){
		try{
			slfClassroomMapper.deleteClassroomPackageMapper(classroomId);
			Map<String,Object> map = new HashMap<String, Object>();
			String[] coursePackageId = coursePackageIds.split(",");
			map.put("coursePackageIds",coursePackageId);
			map.put("classroomId",classroomId);
			slfClassroomMapper.insertClassroomPackageMapper(map);
			ajaxRes.setSucceedMsg(Const.SUCCESS);
		}catch (Exception e){
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}
	
	@RequestMapping("/getClassroomPackage")
	public AjaxRes getClassroomPackage(AjaxRes ajaxRes,Integer classroomId){
		try{
			List<AloneCoursePage> aloneCoursePages = aloneCoursePageDao.getAloneCoursePageOther(classroomId);
			ajaxRes.setSucceed(aloneCoursePages,Const.SUCCESS);
		}catch (Exception e){
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}

	/**
	 * 读取取消预约退钱金额
	 * @param ajaxRes
	 * @param seconds
	 * @param id
	 * @return
	 */
	@RequestMapping("/getCancelMoney")
	public AjaxRes getCancelMoney(AjaxRes ajaxRes,String seconds,Integer id){
		try{
			Integer cancelMoney = commonService.getCancelMoney(seconds,id);
			ajaxRes.setSucceed(cancelMoney,Const.SUCCESS);
		}catch (Exception e){
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}
	
	//我的最近已经上完的课程
	    @RequestMapping("/getnearBy")
		public AjaxRes getnearBy(AjaxRes ajaxRes,Integer classroomId){
			try{
		        //C类	
				Integer userId = ThreadLocalUtil.getUser().getUserId();
				Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
      	//		Integer userId = 274;
				List<SlfChildren> childrenCourse = new ArrayList<SlfChildren>();
				Map<String,Object> map = new HashMap<String, Object>();
		//		List<Integer> childrenIdList = childrenService.getChildrenId(userId);
	           /* for (Integer childrenId : childrenIdList) {*/
	            	map.put("childrenId",childrenId);
	             	SlfChildren slfChildren = childrenService.getAChildren(childrenId);
	             	slfChildren.setChildrenName(slfChildren.getName());
	           // 	SlfChildren slfChildren = new SlfChildren();
	                //C类
	                List<SchoolCoursePage> SchoolCoursePage = schoolCoursePageDao.getChildrenCourseAlready(childrenId);
	                //B类
	                List<SlfMyCoursePage> slfMyCoursePageList = myCoursePageMapper.getChildrenCoursePageAleary(childrenId);
	                slfChildren.setSchoolCoursePage(SchoolCoursePage);
	                slfChildren.setChildrenCoursePage(slfMyCoursePageList);
	                childrenCourse.add(slfChildren);
	            /*}*/
				ajaxRes.setSucceed(childrenCourse,Const.SUCCESS);
			}catch (Exception e){
				ajaxRes.setFailMsg(e.getMessage());
			}
			return ajaxRes;
		}
    // 判断用户是否登陆
    @RequestMapping("/extension")
    public String extension(HttpServletRequest request, HttpServletResponse response) {
        String phone=null;
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("userSession");
        String recommendId="-1";
        if(null != obj) {
            SlfUser user = (SlfUser)obj;
            SlfUser extenSionUser = userService.getExtenSionUser(user.getPhone());
            if(extenSionUser!=null&&extenSionUser.getRecommendId()!=null){
                recommendId=extenSionUser.getRecommendId();
            }
        }else {
            Cookie cookies[] = request.getCookies();
            if(cookies!=null){
                for(int i=0;i<cookies.length;i++){
                    if(cookies[i].getName().equals(CookieUtil.COOKIE_NAME)){
                        phone=cookies[i].getValue();
                        break;
                    }
                }
            }
            if(phone!=null){
                SlfUser user = userService.getUser(Integer.parseInt(phone));
                if(user!=null){
                    recommendId=user.getRecommendId();
                }
            }

        }
        return recommendId;
    }
}
